export function debounce(func: Function, delay: number = 1000, immediate = false) {
  let timer: number | null = null;
  return function(this: any, ...args: any) {
      if (timer) clearInterval(timer)
      if (immediate) {
          if (!timer) func.apply(this, args);
          timer = setTimeout(() => {
              timer = null
          }, delay)
      } else {
          timer = setTimeout(() => {
              func.apply(this, args)
          }, delay)
      }
  }
}

export function throttle(func: Function, delay: number = 1000, immediate = false) {
    if (immediate) {
        let prevTime = 0;
        return function (this: any, ...args: any) {
            const nowTime = Date.now();
            if (nowTime - prevTime >= delay) {
                func.apply(this, args)
                prevTime = nowTime
            }
        }
    } else {
        let timer: number | null = null;
        return function (this: any, ...args: any) {
            if (!timer) {
                timer = window.setTimeout(() => {
                    func.apply(this, args)
                    timer = null
                }, delay);
            }
        }
    }
}

/**
 * @description 移除空字符串，null, undefined
 * @param config 请求参数
 */
export function clearEmptyParam(config: any) {
    ['data', 'params'].forEach(item => {
      if (config[item]) {
        const keys = Object.keys(config[item])
        if (keys.length) {
          keys.forEach(key => {
            const rawType = toRawType(config[item])
            if (['', undefined, null].includes(config[item][key]) &&
                ['Object'].includes(rawType)) {
              delete config[item][key]
            }
          })
        }
      }
    })
  }
  
  /**
   * @description 获取原始类型
   * @param {*} value
   * @returns {String} 类型字符串，如'String', 'Object', 'Null', 'Boolean', 'Number', 'Array'
   */
  export function toRawType(value: any) {
    return Object.prototype.toString.call(value).slice(8, -1)
  }

  export function isInViewport(element: HTMLElement) {
    const observer = new IntersectionObserver(
      ([entry]) => {
        console.log(entry, entry.isIntersecting);
        return entry.isIntersecting
      },
      {
        root: null,
        rootMargin: '0px',
        threshold: 0
      }
    )
    observer.observe(element)
  }